#! /usr/bin/env python3

import argparse

default_num_clusters = 2
default_max_pattern_size = 21
default_max_dynamic_pd_size = 0

import misc.utils as utils

def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="Create a pattern database file using the "
        "'Compoent Grouping' scheme from Fan and Yuan, AAAI 2015. Then, use it and the "
        "decomposition from UAI 2014.")
    parser.add_argument("pss", help="The pss file containing the local scores")
    parser.add_argument("-n", "--net", help="The output file containing the learned "
        "network structure.", default="")

    parser.add_argument('-d', '--max-dynamic-pd-size', help="The maximum size of the patterns "
        "used in dynamic pattern databases", type=int, default=default_max_dynamic_pd_size)
    parser.add_argument('-c', '--num-clusters', help="The number of clusters to use, but "
        "only in case of the parent grouping.", type=int, default=default_num_clusters) 
    parser.add_argument('-s', '--max-pattern-size', help="The maximum size allowed in "
        "creating the component grouping pattern database", type=int,default=default_max_pattern_size)
    parser.add_argument('--do-not-call', action='store_true')


    utils.add_logging_options(parser)
    args = parser.parse_args()
    utils.update_logging(args)

    programs =  [   'create-component-grouping-pd',
                    'astar-decomposition',
                    'astar',                        # from astar-decomposition
                    'merge-networks'                # from astar-decomposition
                ]

    utils.check_programs_exist(programs)
    call = not args.do_not_call

    logging_str = utils.get_logging_options_string(args)

    pd_file = "{}.component-grouping.pd".format(args.pss)

    cmd = ( "create-component-grouping-pd {} {} --max-dynamic-pd-size {} --num-clusters {} "
            "--max-pattern-size {} {}".format(args.pss, pd_file, args.max_dynamic_pd_size, 
            args.num_clusters, args.max_pattern_size, logging_str))
    #in_files = [args.pss]
    #out_files = [pd_file]
    #utils.call_if_not_exists(cmd, out_files, in_files=in_files, call=call)
    utils.check_call(cmd, call=call)

    net_str = ""
    if len(args.net) > 0:
        net_str = "-n {}".format(args.net)

    cmd = "astar-decomposition {} -p {} {} {}".format(args.pss, pd_file, logging_str, net_str)
    utils.check_call(cmd)

if __name__ == '__main__':
    main()

